//
//  RHBlockPCSParaVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/10/26.
//

#import "RHBlockPCSParaVC.h"
#import "RHCommonDataCell.h"
//#import "RHDevEMSModel.h"
#import "RHDevDataModel.h"
#import "SYChartTool.h"

@interface RHBlockPCSParaVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) NSMutableDictionary *dataDic;
@end

@implementation RHBlockPCSParaVC
-(NSMutableDictionary *)dataDic
{
    if(!_dataDic){
        _dataDic = [NSMutableDictionary dictionary];
    }
    return _dataDic;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"PCS运行参数".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
    [self getPCSData];
}

-(void)setupUI{
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"Dev_pcs_rundata"];
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHDevEndPointDataModel class] json:arr];
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonNormalCell];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    _tableView.estimatedRowHeight = 180;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.tableFooterView = [UIView new];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf getPCSData];
    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}
#pragma mark --------- network ----------
//获取pcs数据
-(void)getPCSData
{
 
    [QMUITips showLoadingInView:self.view];
    
    NSArray *pcsParas = @[@"Pcs_GridInterCnctMode",
                          @"Pcs_TtlACAtvPwr",
                          @"Pcs_TtlACAtvPwr",
                          @"Pcs_TtlACRtvPwr",
                          @"Pcs_TtlACaptPwr",
                          @"Pcs_TtlACPF",
                          @"Pcs_Ambient_Tmp",
                          @"Pcs_Mdl_Tmp"
    ];
    
    NSDictionary *para = @{@"deviceId":self.deviceModel.deviceId,
                           @"endpointTypeCode":@"PCS",
                           @"keyCodes":pcsParas,
                           @"endpointSn":ValidNullData(self.curEMSModel.pcsSn)
    };
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
              
                self.dataDic = [NSMutableDictionary dictionaryWithDictionary:request.responseObject[@"data"]];
                [self getMasterData];
               
                
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

-(void)getMasterData
{
    [QMUITips showLoadingInView:self.view];
    NSArray *masterParas = @[@"Mtr_TV",
                          @"Mtr_Cur"
    ];
    
    NSDictionary *para = @{@"deviceId":self.deviceModel.deviceId,
                           @"endpointTypeCode":@"Master",
                           @"keyCodes":masterParas,
                           @"endpointSn":self.curMasterModel.sn
    };
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                [self.dataDic addEntriesFromDictionary:request.responseObject[@"data"]];
                [self updateData:self.dataDic];
                
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

-(void)updateData:(NSDictionary*)dic
{
    //直流功率
    __block RHDevDataModel *model ;
    //变流器效率
    __block RHDevDataModel *pw_model ;
    [self.dataArr enumerateObjectsUsingBlock:^(RHDevEndPointDataModel  *_Nonnull masterModel, NSUInteger idx, BOOL * _Nonnull stop) {
        masterModel.data = dic;
        //直流功率
        [masterModel.infoArr enumerateObjectsUsingBlock:^(RHDevDataModel  *_Nonnull dataModel, NSUInteger idx, BOOL * _Nonnull stop) {
            if([dataModel.alias isEqualToString:@"直流功率"]){
                model = dataModel;
            }
            if([dataModel.alias isEqualToString:@"变流器效率"]){
                pw_model = dataModel;
            }
            
        }];
    }];
    //直流功率
    double value = [ValidNullData(dic[@"Mtr_TV"]) doubleValue] * [ValidNullData(dic[@"Mtr_Cur"]) doubleValue];
    model.content = [[NSNumber numberWithDouble:value]twoDecimalPlacesWithoutRounding];
    //变流器效率
    double pw_value = [ValidNullData(dic[@"Pcs_TtlACAtvPwr"]) doubleValue];
    if(pw_value == 0.0){
        pw_model.comment = @"0";
    }else{
        pw_model.content = [[NSNumber numberWithDouble:value]twoDecimalPlacesWithoutRounding];
    }
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    RHDevEndPointDataModel *masterModel = self.dataArr[section];
    return masterModel.infoArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    RHDevEndPointDataModel *emsModel = self.dataArr[section];
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 60)];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 10, kUI_WINDOW_W-30, 50)];
    [headView addSubview:bgView];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bgView.backgroundColor = [UIColor whiteColor];
    UIImageView *icon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:emsModel.icon]];
    [bgView addSubview:icon];
    
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kSYSTEMFONT(15);
    titleLab.textColor = kColorRGB(0, 0, 0);
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = emsModel.title;
    [bgView addSubview:titleLab];
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [bgView addSubview:line];
    
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(icon.mas_right).offset(15);
        make.centerY.equalTo(icon);
     }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(1);
        make.bottom.mas_offset(-5);
    }];
   return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 20)];
    footer.backgroundColor = CFTabViewBgColor;
    UIView *subView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, footer.width-30, 10)];
    subView.backgroundColor = [UIColor whiteColor];
    subView.layer.cornerRadius = 8;
    subView.layer.masksToBounds = YES;
    subView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    [footer addSubview:subView];
    return footer;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHCommonDataCell *cell = [tableView dequeueReusableCellWithIdentifier:CommonNormalCell];
    RHDevEndPointDataModel *masterModel = self.dataArr[indexPath.section];
    cell.dataModel = masterModel.infoArr[indexPath.row];
    return cell;
}






@end
